// pages/profile/profile.js
const app = getApp()

Page({
  data: {
    userInfo: null,
    stats: {
      likes: 0,
      matches: 0,
      visitors: 0
    },
    likedUsers: [],
    isLoading: true
  },

  onLoad() {
    this.checkAuthAndLoadData();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.setData({ userInfo: app.globalData.userInfo });
      this.loadUserStats();
    }
  },

  // 检查授权并加载数据
  checkAuthAndLoadData() {
    if (app.globalData.userInfo) {
      this.setData({ userInfo: app.globalData.userInfo });
      this.loadUserStats();
    } else {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },

  // 加载用户统计数据
  loadUserStats() {
    this.setData({ isLoading: true });

    // 加载喜欢的人
    this.loadLikedUsers();
    
    // 使用模拟数据
    if (app.globalData.useMockData) {
      setTimeout(() => {
        this.setData({
          stats: {
            likes: 24,
            matches: 8,
            visitors: 156
          },
          isLoading: false
        });
      }, 1000);
      return;
    }

    // 实际API调用逻辑
    this.loadUserStatsFromAPI();
  },

  // 加载喜欢的人
  loadLikedUsers() {
    const likedUsers = wx.getStorageSync('likedUsers') || [];
    this.setData({
      likedUsers: likedUsers,
      stats: {
        ...this.data.stats,
        likes: likedUsers.length
      }
    });
  },

  // 从API加载用户统计数据
  async loadUserStatsFromAPI() {
    try {
      const result = await wx.request({
        url: `${app.globalData.baseUrl}/users/stats`,
        method: 'GET',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        }
      });

      if (result.data.success) {
        this.setData({
          stats: result.data.data.stats || {},
          isLoading: false
        });
      } else {
        app.showError(result.data.message || '加载失败');
        this.setData({ isLoading: false });
      }
    } catch (error) {
      console.error('加载用户数据失败:', error);
      app.showError('网络错误，请重试');
      this.setData({ isLoading: false });
    }
  },

  // 编辑个人资料
  editProfile() {
    wx.navigateTo({
      url: '/pages/profile/edit'
    });
  },

  // 查看喜欢我的人
  viewLikes() {
    wx.navigateTo({
      url: '/pages/likes/list'
    });
  },

  // 查看匹配
  viewMatches() {
    wx.navigateTo({
      url: '/pages/matches/list'
    });
  },

  // 查看访客
  viewVisitors() {
    wx.navigateTo({
      url: '/pages/visitors/list'
    });
  },

  // 设置
  goToSettings() {
    wx.navigateTo({
      url: '/pages/settings/index'
    });
  },

  // 帮助与反馈
  goToHelp() {
    wx.navigateTo({
      url: '/pages/help/index'
    });
  },

  // 关于我们
  goToAbout() {
    wx.navigateTo({
      url: '/pages/about/index'
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          
          // 清除全局数据
          app.globalData.token = null;
          app.globalData.userInfo = null;
          
          // 跳转到登录页
          wx.redirectTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  },

  // 分享个人资料
  shareProfile() {
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  // 上传头像
  uploadAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadImageToServer(tempFilePath, 'avatar');
      }
    });
  },

  // 上传图片到服务器
  async uploadImageToServer(filePath, type) {
    wx.showLoading({
      title: '上传中...'
    });

    try {
      const result = await wx.uploadFile({
        url: `${app.globalData.baseUrl}/users/upload-${type}`,
        filePath: filePath,
        name: 'file',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        }
      });

      const data = JSON.parse(result.data);
      if (data.success) {
        // 更新用户信息
        const userInfo = { ...this.data.userInfo };
        if (type === 'avatar') {
          userInfo.avatar_url = data.data.url;
        }
        
        this.setData({ userInfo });
        app.globalData.userInfo = userInfo;
        wx.setStorageSync('userInfo', userInfo);
        
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        app.showError(data.message || '上传失败');
      }
    } catch (error) {
      console.error('上传失败:', error);
      app.showError('上传失败');
    } finally {
      wx.hideLoading();
    }
  }
})
